//
//  UIImageView+Fade.m
//  UIImageView+AnimationForSDWebImage
//
//  Created by 王鹏宇 on 2017/7/18.
//  Copyright © 2017年 penghe. All rights reserved.
//

#import "UIImageView+Fade.h"
#import "FileManager.h"
#import <SDWebImage/UIImageView+WebCache.h>

@implementation UIImageView (Fade)

- (void)setImageURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
    
    
    self.image = placeholder;
    
    UIImage *image = [UIImageView imageFromDiskCacheForKey:url.absoluteString];
    
    if (image) {
        self.image = image;
        return;
    }
    
    @weakify(self);
    [self sd_setImageWithURL:url placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        @strongify(self);
        if (image && cacheType == SDImageCacheTypeNone) {
        
            CATransition *transition = [CATransition animation];
            transition.type = kCATransitionFade;
            transition.duration = 0.5;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            [self.layer addAnimation:transition forKey:nil];
        }
     
    }];
}

+ (UIImage *)imageFromDiskCacheForKey:(NSString *)url {
    
    UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromCacheForKey:url];
    
    if (!image) {
        image = [FileManager getImageInDirectory:kPath_ImageSave url:url];
        [[SDWebImageManager sharedManager].imageCache storeImage:image forKey:url completion:nil];
    }
    
    return image;
}

@end
